package com.learning.js_cookieandsession;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;

@WebServlet(name = "CookieServlet1", value = "/demo1")
public class MyCookie extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 创建Cookie
        Cookie cookie = new Cookie("name", "value");

        // 设置cookie的属性
        cookie.setMaxAge(3600); // 设置有效期为1小时
        cookie.setDomain("example.com");
        cookie.setPath("/");

        // 放入响应对象中
        response.addCookie(cookie);

        // 从request中获取Cookies
        Cookie[] cookies = request.getCookies();

// 遍历Cookies
        Arrays.stream(cookies).forEach(cookie2 -> {
            System.out.println(cookie.getName() + ": " + cookie.getValue());
        });

        response.sendRedirect("MyCookie.jsp");
    }



}
